"use client";

import { Button, Divider, message, Row, Upload } from "antd";
import { MdSaveAs } from "react-icons/md";
import { VscError } from "react-icons/vsc";
import { getUserAccount } from "../../utils/defender";
import { UploadOutlined } from "@ant-design/icons";
import { useState } from "react";
import { UpLoadAppendix } from "@/app/api/operation/query";

export interface SignPropType {
  docid: string;
  onCancel: () => void;
  onSubmit: (docid: string) => void;
}

export default function PushFlow(props: SignPropType) {
  const [file, setFile] = useState<any>();

  const Submit = async () => {
    if(!file){
        message.info('請上傳文件');
        return false
    } 
    const formdata = new FormData();
    formdata.append("docid", props.docid);
    formdata.append("file", file);
    formdata.append("filename", file.name);
    formdata.append("username", getUserAccount() as string);
    try {
      const res: any = await UpLoadAppendix(formdata);
      if (res === "success") {
        setFile('')
        props.onSubmit(props.docid);
      }
    } catch {
      message.error("系統異常");
    }
  };

  const upLoadChange = (file: any) => {
    //上傳文件時文件名簡體中文，繁體中文檢測
    const regexChinese = /[\u4e00-\u9fa5，。]/g;
    const regexChineseComplicate = /[\u4E00-\u9FFF\u3400-\u4DBF]/;
    if (
      !regexChinese.test(file.name) &&
      !regexChineseComplicate.test(file.name)
    ) {
      setFile(file.originFileObj);
    } else {
      message.error("請不要使用中文檔名");
    }
  };

  const Cancle = () => {
    props.onCancel();
  };
  return (
    <div>
      <h4 style={{ margin: "5px 0", color: "black" }}>強制執行下一步流程</h4>
      <Divider style={{background:'brown'}}></Divider>
      <Row>
        <Upload maxCount={1} onChange={(file) => upLoadChange(file.file)}>
          <Button
            type="primary"
            shape="round"
            icon={<UploadOutlined />}
            style={{ marginLeft: "10px" }}
          >
            上傳文件
          </Button>
        </Upload>
      </Row>
      <Row style={{ marginTop: "20px", textAlign: "center" }}>
        <Button
          icon={<MdSaveAs></MdSaveAs>}
          color="default"
          style={{ marginLeft: "10px" }}
          onClick={() => {
            Submit();
          }}
        >
          確定
        </Button>
        <Button
          onClick={() => Cancle()}
          icon={<VscError></VscError>}
          type="primary"
          danger
          style={{ marginLeft: "30px" }}
        >
          取消
        </Button>
      </Row>
    </div>
  );
}
